//
//  AliPayOrder.m
//  EasyToTesco2.0
//
//  Created by knew on 16/9/13.
//  Copyright © 2016年 EasyToTesco. All rights reserved.
//

#import "AliPayOrder.h"
#import "Order.h"
#import "RSA.h"
#import <AlipaySDK/AlipaySDK.h>
#import <UIKit/UIKit.h>

@interface AliPayOrder ()

@property (nonatomic,copy)NSString *dataString;

@end

@implementation AliPayOrder

#pragma mark >>>>>>>> 支付宝支付
+ (void)doAlipayPayWithOrderNumber:(NSString *)orderNumber andOrderAllPrice:(NSString *)orderPrice andOrderBodyTitle:(NSString *)orderBody andOrderSubject:(NSString *)orderSubject andBackDataBlock:(CompleteBlock)completeBlock andMBPView:(UIView *)view
{
    //重要说明
    //这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
    //真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
    //防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
    /*============================================================================*/
    /*=======================需要填写商户app申请的===================================*/
    /*============================================================================*/
    NSString *appID = ALI_APPID;
    NSString *privateKey = ALI_PrivateKey;
    /*============================================================================*/
    /*============================================================================*/
    /*============================================================================*/
    
    //partner和seller获取失败,提示
    if ([appID length] == 0 ||
        [privateKey length] == 0)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"缺少appId或者私钥。"
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        return;
    }
    
    /*
     *生成订单信息及签名
     */
    //将商品信息赋予AlixPayOrder的成员变量
    Order* order = [Order new];
    
    // NOTE: app_id设置
    order.app_id = appID;
    
    // NOTE: 支付接口名称
    order.method = @"alipay.trade.app.pay";
    
    // NOTE: 参数编码格式
    order.charset = @"utf-8";
    
    // NOTE: 当前时间点
    NSDateFormatter* formatter = [NSDateFormatter new];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    order.timestamp = [formatter stringFromDate:[NSDate date]];
    
    // NOTE: 支付版本
    order.version = @"1.0";
    
    // 回调
    order.notify_url = @"http://www.dev.ylgw8.com/api/Pay/alipay_notity?";
    
    // NOTE: sign_type设置
    order.sign_type = @"RSA";
    
    // NOTE: 商品数据
    order.biz_content = [BizContent new];
    order.biz_content.body = orderBody;
    order.biz_content.seller_id = @"2088421736439786";
    order.biz_content.subject = orderSubject;
    order.biz_content.out_trade_no = orderNumber; //订单ID（由商家自行制定）
    order.biz_content.timeout_express = @"30m"; //超时时间设置
#warning 设置商品价格
        order.biz_content.total_amount = [NSString stringWithFormat:@"%@", orderPrice]; //商品价格
//    order.biz_content.total_amount = @"0.01";
//    //将商品信息拼接成字符串
    NSString *orderInfo = [order orderInfoEncoded:NO];
    //    NSString *orderInfoEncoded = [order orderInfoEncoded:YES];
    NSLog(@"orderSpec = %@",orderInfo);
    
    // NOTE: 获取私钥并将商户信息签名，外部商户的加签过程请务必放在服务端，防止公私钥数据泄露；
    //       需要遵循RSA签名规范，并将签名字符串base64编码和UrlEncode
    
    NSDictionary *params = @{
                             @"app_id":ALI_APPID,
                             @"biz_content":@{
                                     @"timeout_express":@"30m",
                                     @"seller_id":@"2088421736439786",
                                     @"product_code":@"QUICK_MSECURITY_PAY",
                                     @"total_amount":order.biz_content.total_amount,
                                     @"subject":order.biz_content.subject,
                                     @"body":order.biz_content.body,
                                     @"out_trade_no":orderNumber
                                     },
                             @"charset":@"utf-8",
                             @"method":@"alipay.trade.app.pay",
                             @"notify_url":@"http://www.dev.ylgw8.com/api/Pay/alipay_notity?",
                             @"sign_type":@"RSA",
                             @"timestamp":order.timestamp,
                             @"version":@"1.0",
                             @"partner":ALI_APPID,
                             @"service":@"mobile.securitypay.pay"
                             };
        
        [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"/api/Pay/alipay_sign" completeBlock:^(id object) {
            
            if (JudgeBackDataCode) {
   
                // NSString *signedString = [RSA signString:orderInfo withPrivatekey:ALI_PrivateKey];
                
                // NSString *orderString = [NSString stringWithFormat:@"%@&sign=%@",orderInfo,signedString];
    
                NSString *appScheme = @"EasyToTesco2";
    
                // NOTE: 将签名成功字符串格式化为订单字符串,请严格按照该格式
                NSString *orderString = [NSString stringWithFormat:@"%@&sign=%@",
                                             orderInfo, object[@"data"]];
                    
                // NOTE: 调用支付结果开始支付
                [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
        
                    if (completeBlock) {
                        completeBlock(resultDic);
                    }
        
                }];
    
            } else {
                MBProgressHUD *hud = [MBProgressHUD showMessage:@"支付失败,请稍后再试" toView:view dimBackground:NO AndCompleteBlock:nil];
                [view addSubview:hud];
            }
        }];
}



@end
